<template>
  <div ref="map" class="map"></div>
  <map-detail v-if='isShowDetail' :projectId='projectId' :title='projectName' @closeDetail="closeDetail"></map-detail>
</template>

<script setup lang="ts">
import { ECharts } from "echarts";
import echarts from "/@/plugins/echarts";
import { onMounted, nextTick, ref, watch } from "vue";
import { tryOnUnmounted, useTimeoutFn, useEventListener } from "@vueuse/core";
import {
  addResizeListener,
  removeResizeListener
} from "element-plus/lib/utils/resize-event";
 import {
    getStatictisA
  } from "/@/api/board";
  import NotifMessage from "/@/utils/message/notification";
import axios from "axios";
import mapDetail from "./mapDetail.vue";
// const props = defineProps({
//   dataList: {
//     type: Array,
//     default: () => []
//   }
// });
// const emit = defineEmits(["clickItem", "cancleSelected"]);
let mapOriginaDate = ref([]);
let projectId = ref("");
let projectName = ref("");
const isShowDetail = ref(false)
const map = ref<HTMLElement | null>(null) as any;
let echartInstance: ECharts;
let seriesData = ref([]);
let selectedName = ref("");
let option = {} as any;
let geoData = null;
const showDialog = async() =>{
  console.log("1111111");
  // if(!params?.projectId){
  //   NotifMessage.error("暂无详情数据");
  //   return
  // }
  // selectedName.value = params?.projectRegionName;
  // projectName.value = params?.projectName
  // projectId.value = params?.projectId
  isShowDetail.value = true;
}
const getdata = async () => {
  if (!geoData) {
    axios.get("./json/china_1.json").then(data => {
      geoData = data.data;
      echarts.registerMap("china", { geoJSON: translateMapData(geoData) });
      initechartInstance(seriesData.value);
    });
  } else {
    setOption(seriesData.value);
  }
};

//给地图数据添加地区
const  translateMapData = (source) =>{
  const customMap = [
    {
      name: '华南生产部',
      include: ["湖北省", "湖南省", "广东省", "海南省"],
      center: [114.298572, 30.584355],
      coordinates: []
    },
    {
      name: '华东生产部',
      include: ["浙江省", "江苏省", "上海市", "安徽省", "苏沪省"],
      center: [120.153576, 30.287459],
      coordinates: []
    },
    {
      name: '华北生产部',
      include: ["天津省", "河北省", "山东省"],
      center: [117.190182, 39.125596],
      coordinates: []
    },
    {
      name: '东北生产部',
      include: ["内蒙古自治区", "辽宁省", "黑吉省"],
      center: [123.429096, 41.796767],
      coordinates: []
    },
    {
      name: '西北生产部',
      include: ["山西省", "晋陕省", "陕西省", "甘青藏省", "甘肃省", "宁夏回族自治区", "西藏", "河南省"],
      center: [123.429096, 41.796767],
      coordinates: []
    },
    {
      name: '西南生产部',
      include: ["四川省", "贵州省", "广西壮族自治区"],
      center: [104.065735,30.659462],
      coordinates: []
    },
    {
      name: '总部',
      include: ["北京市"],
      center: [116.405285, 39.904989],
      coordinates: []
    },
    {
      name: '华润啤酒总部',
      include: ["北京市"],
      center: [116.405285, 39.904989],
      coordinates: []
    }
  ]

  customMap.forEach(item => {
    source.features.forEach(targetItem => {
      if (item.include.includes(targetItem.properties.name)) {
        if(['甘青藏省', '黑吉省', '内蒙古自治区', '晋陕省'].includes(targetItem.properties.name)) {
          item.coordinates.push(targetItem.geometry.coordinates)
        } else {
          item.coordinates = item.coordinates.concat(targetItem.geometry.coordinates)
        }
        targetItem.isJoin = true
      }
    })
  })
  const transleted = customMap.map(item => {
    return {
      type: "Feature",
      properties: {
        name: item.name,
        center: item.center
      },
      geometry: {
        type: "MultiPolygon",
        coordinates: item.coordinates
      }
    }
  })
  return {
    type: "FeatureCollection",
    features: [...transleted, ...source.features.filter(item => !item.isJoin)]
  }
}


//初始化地图配置项
const initechartInstance = (chartData) => {
  chartData.forEach(item => {
    if (item.name === '喜力生产部') {
      item.name = '总部/喜力生产部'
    }
  })
  const echartDom = document.querySelector(".map");
  if (!echartDom) return;
  // @ts-ignore
  echartInstance = echarts.init(echartDom, null, {});
  echartInstance.clear(); //清除旧画布 重新渲染
  option = {
    tooltip: {
      show: true,
      enterable:true,
      confine: true,
      trigger:'item',
      triggerOn: 'click',
      // extraCssText: "z-index: 9999",
      // alwaysShowContent: true,
      backgroundColor: "rgba(0, 21, 43, 0.6)",
      textStyle: {
        color: "#FDFDFF",
        fontSize: "14px"
      }, //提示标签字体颜色
      borderWidth: 2,
      borderColor: "#8895B7",
      formatter: function (params) {
        var nameArr = params.seriesName.split(",");
        var num1 = 0;
        if (!isNaN(params.value)) {
          num1 = params.value;
        }
        let index = params.name.indexOf("省");
        let name = index > -1 ? params.name.slice(0, index) : params.name;
        name = name.indexOf("总部基地项目组") > -1 ? name : name + "<br />";
        return name + nameArr[0] + "：" + num1;
      },
    },

      visualMap: [{
        min: 1,
        max: 3,
        bottom: 100,
        text: ["高", "中", "低"],
        precision:0,
        hoverLink:true,
        inRange: {
          color: ["#2EB82E",'#0073E5','#FAAD14']
        },
        show: false
      }
    ],
    geo: {
      zlevel: -1,
      map: 'china',
      aspectScale: 0.85,
      zoom: 1.5,
      top: '34%',//***********重点**********距离顶部的位置，每层向下一个百分比
      right: '5%',
      roam: false,
      z: 3,//*********重点*********可以看成是css的z-index，数字越大图层越高，我这里设置了5个，然后页面有点卡，根据实际需要来添加，3个其实就能看出效果了
      regions: [
        { // 隐藏南海诸岛,因为顶层已经添加过了
          name: '南海诸岛',
          itemStyle: {
            normal: {
              opacity: 0 // 为 0 时不绘制该图形
            }
          },
          label: {
            show: false
          }
        }
      ],
      label: {
        show: false,
        formatter: params => {
          let index = params.name.indexOf("省");
          let name = index > -1 ? params.name.slice(0, index) : params.name;
          name = name.indexOf("总部基地项目组") > -1 ? name : name;
          return name;
        }
      },
      itemStyle: {
        areaColor: '#BFD6F0', //地图的颜色
        borderColor: '#BFD6F0', //边界线颜色
        borderWidth: 2, //边界线宽
        normal: {
          borderWidth: 2,//区域边框宽度
          borderColor: '#BFD6F0',//区域边框颜色
          areaColor: "#BFD6F0",//区域颜色
        },
      },
      emphasis: {
        disabled: true, //是否可以被选中
        label: {
          show: false,
          textStyle: { color: "#2EB82E" },
          color: '#2EB82E',
          areaColor: '#AAE5A1',
          borderColor: '#AAE5A1',
          borderWidth: 2,
        },
        itemStyle: {
          areaColor: '#2EB82E', //地图的颜色
          borderColor: '#2EB82E', //边界线颜色
          borderWidth: 2, //边界线宽
        }
      },
      tooltip: {
        show: false,
        trigger: 'item',
        triggerOn: 'mousemove', // 只在鼠标移动时触发
        backgroundColor: "#2EB82E",//提示标签背景颜色
        textStyle: { color: "#fff" }, //提示标签字体颜色
        borderColor: '#2EB82E',
        borderWidth: 2,
        formatter: (params) => {
          console.log(params,"0000")
          return params.name + ' : ' + (Number(params.value) > 0 ? params.value : '0')
        }
      },
      selectedMode: "single",
      select: {
        disabled:true,
        itemStyle: {
          areaColor: "#3E8CFF",
          borderColor: "#3E8CFF"
        },
        label: {
          show:false
        }
      }
    }
  };
  setOption(chartData);

  echartInstance.on("click", (params) => {
    // echartInstance.dispatchAction({
    //   type: "showTip",
    //   name:params.name
    // });
    selectedName.value = params.name;
  });

  echartInstance.on("showTip",() => {
    const tooltipContent = document.querySelectorAll('.my-tool');
    if (tooltipContent?.length) {
      for (let i = 0; i < tooltipContent.length; i++) {
        tooltipContent[i].addEventListener('click', e => {
          const target = e.target as HTMLElement
          const id = target.getAttribute('data-id')
          const name = target.getAttribute('data-name')
          projectName.value = name;
          projectId.value = id;
          isShowDetail.value = true;
        })
      }
    }
  })

  // 监听点击非地图区域
  echartInstance.getZr().on("click", function (event) {
    if (!event.target) {
      echartInstance.dispatchAction({
        type: "unselect",
        name:selectedName.value
      });
    }
  });
}

const closeDetail = () => {
  isShowDetail.value = false;
}
const setOption = chartData => {
  // window.showDialog = showDialog()
  option.series = [
    {
      type: 'map',
      map: 'china',
      coordinateSystem: 'geo',
      aspectScale: 0.85, //长宽比
      mapType: 'china',
      symbolSize: 12,
      zoom: 1.5,
      roam: false, //鼠标缩放关闭
      top: '24%',
      right: "3%",
      // itemStyle: {
      //   areaColor: '#BFD6F0', //地图的颜色
      //   borderColor: '#BFD6F0', //边界线颜色
      //   borderWidth: 2, //边界线宽
      //   normal: {
      //     borderWidth: 2,//区域边框宽度
      //     borderColor: '#BFD6F0',//区域边框颜色
      //     areaColor: "#BFD6F0",//区域颜色
      //   },
      // },

      itemStyle: {
        areaColor: '#DFEBF7',//****重点****每个图层的背景色，根据需要来调，由亮变暗，下面的几个颜色也一样
        borderColor: '#DFEBF7',
        borderWidth: 2,
        opacity: 1
      },
      label: {//标签
        fontSize: 12,
        normal: {
          show: false, // 是否显示省份标签
          color: '#0073E5',
          textStyle: { color: "#0073E5" },//省份标签字体颜色
          formatter: '{b}',
          position: 'center',
        }
      },
      emphasis: { // 对应的鼠标悬浮效果
        label:{
          show:false
        },
        textStyle: { color: "#2EB82E" },
        color: '#2EB82E',
        itemStyle: {
          areaColor: '#5298FF',
          borderColor: '#5298FF',
          borderWidth: 1
        }
      },
      tooltip: {
        show: true,
        padding:0,
        backgroundColor: "rgba(236, 255, 232, 0.48)",//提示标签背景颜色
        textStyle: { color: "#2EB82E",fontSize:12 }, //提示标签字体颜色
        borderColor: 'linear-gradient(251deg, #2EB82E 21%, #9DEB87 98%) 1;',
        borderWidth: 0,
        formatter: (params) => {
          let toolData = mapOriginaDate.value.filter(ele => ele.projectRegionCode === params.data?.code);
          const styleMap = {
            bg_1:"linear-gradient(114deg, rgba(249, 255, 247, 0.91) 8%, rgba(236, 255, 232, 0.48) 98%);",
            borBg_1:'linear-gradient(251deg, #2EB82E 21%, #9DEB87 98%) 1',
            color_1:"#2EB82E;",

            bg_2:"linear-gradient(114deg, #F4F9FF 8%, #33E6F2FF);",
            borBg_2:'linear-gradient(251deg, #0073E5 21%, #8BC5FF 98%) 1;',
            color_2:"#0073E5;",

            bg_3:"linear-gradient(114deg, #FFFDFA 8%, #7aFFF9EC);",
            borBg_3:'linear-gradient(251deg, #FAAD14 21%, #FFD633 98%) 1;',
            color_3:"#EEA209;",
          }
          let htmlDiv = '<div style="width:100%;height:100%"><div style="border-radius: 6px;padding:6px;background-color:'+styleMap["bg_"+params?.data?.progress]+';border:2px solid;borderColor:'+styleMap["borBg_"+params?.data?.progress]+';color:'+styleMap["color_"+params?.data?.progress]+'">'
            if(toolData?.length){
              toolData.forEach((ele,index) => {
                htmlDiv +=  '<div style="color:'+styleMap["color_"+ele?.projectSectionStatictisDto?.progress]+';cursor:pointer" class="my-tool">\
                      <span style="margin-right: 5px;" @click="'+showDialog+'" data-id="'+ele.projectId+'"  data-name="'+ele.projectName+'">'+ele.projectRegionName+'</span>\
                      <span data-id="'+ele.projectId+'"  data-name="'+ele.projectName+'">'+(ele.projectName || "")+'</span>\
                    </div>'
              })
              htmlDiv += '</div>'
            }
            else{
              htmlDiv +=  '<div>\
                  <span style="margin-right: 5px;">'+params.name+'</span>\
                  <span>'+(params.data?.projectName || "")+'</span>\
                </div>'
              htmlDiv += '</div></div>'
            }
          return htmlDiv;
        }
      },
      selectedMode: "single",
      select: {
        itemStyle: {
          areaColor: "#3E8CFF",
          borderColor: "#3E8CFF"
        },
        label: {
          show:false
        }
      },
      data:chartData
    }
  ];
  const seriesData = option.series[0];
  const mapData = seriesData?.data || [];
  if(mapData?.length){
    seriesData.data
  }
  echartInstance.setOption(option);
};

//获取项目数据
const getStatictisData = async () => {
  try {
    const { code, data, message } = await getStatictisA(0);
    if (code === 200) {
      mapOriginaDate.value = JSON.parse(JSON.stringify(data));
      let uniqueArray = data.filter((item, index, arr) => {
        return arr.findIndex(obj => obj.projectRegionCode === item.projectRegionCode) === index; // 只保留第一次出现的项。
      });
      seriesData.value = uniqueArray?.map(ele => {
        return {
          name:ele?.projectRegionName,
          value:Number(ele?.projectSectionStatictisDto?.progress),
          id:ele?.projectId,
          progress:ele?.projectSectionStatictisDto?.progress,
          code:ele?.projectRegionCode,
          projectId:ele?.projectId,
          projectName:ele?.projectName
        }
      }) || [];
      if(seriesData.value?.length){
        nextTick(() => {
          getdata();
          addResizeListener(map.value, resetRender);
        });
      }
    }
    else {
      NotifMessage.error(message || "获取数据异常");
    }
  } catch (err) {
    console.log(err);
  }
}

// watch(
//   () => props.dataList,
//   newVal => {
//     seriesData.value = newVal;
//     getdata();
//   }
// );
onMounted(() => {
  getStatictisData()
  useEventListener("resize", () => {
    resetRender();
  });
});

const resetRender = () => {
  if (!echartInstance) return;
  useTimeoutFn(() => {
    echartInstance.resize();
  }, 180);
};

// const setMapSelect = name => {
//   selectedName.value = "";
//   echartInstance.dispatchAction({
//     type: "select",
//     name
//   });
// };
// const setMapUnSelect = name => {
//   echartInstance.dispatchAction({
//     type: "unselect",
//     name
//   });
// };
// defineExpose({ setMapSelect, setMapUnSelect });

tryOnUnmounted(() => {
  if (!echartInstance) return;
  echartInstance.dispose();
  echartInstance = null;
  removeResizeListener(map.value, resetRender);
});

</script>

<style scoped>
  .map{
    width: 33%;
    height: 300px;
    background: #fff;
  }
</style>
